package wxcloud

import (
	"context"
	"encoding/json"
	"fmt"
	"time"

	"github.com/mars/internal/admin/core/domain"
	"github.com/mars/internal/pkg/wxcloud"
)

const (
	userCollection = "user" // 用户集合名称
)

type UserGatewayImpl struct {
	wxcloud *wxcloud.WxCloudClient
}

var _ domain.UserGateway = (*UserGatewayImpl)(nil)

func newUserGatewayImpl(wxcloud *wxcloud.WxCloudClient) *UserGatewayImpl {
	return &UserGatewayImpl{wxcloud: wxcloud}
}

// Users 查询所有用户信息
func (u *UserGatewayImpl) Users(ctx context.Context) ([]domain.User, int64, error) {
	// 构建查询语句
	query := wxcloud.NewQueryBuilder(userCollection).
		Limit(1000). // 限制最多1000条
		OrderBy("createTime", "desc").
		BuildQueryString()

	// 查询用户数据
	resp, err := u.wxcloud.DatabaseQuery(ctx, u.wxcloud.EnvId(), query)
	if err != nil {
		return nil, 0, fmt.Errorf("failed to query users: %w", err)
	}

	// 转换数据
	users := make([]domain.User, 0, len(resp.Data))
	for _, item := range resp.Data {
		var user domain.User
		if err := json.Unmarshal([]byte(item), &user); err == nil {
			users = append(users, user)
		} else {
			return nil, 0, err
		}
	}
	return users, int64(resp.Pager.Total), nil
}

// User 根据用户openid查询用户信息
func (u *UserGatewayImpl) User(ctx context.Context, openid string) (*domain.User, error) {

	// 构建查询语句
	query := wxcloud.NewQueryBuilder(userCollection).
		Where("openid", openid).
		Limit(1).
		BuildQueryString()

	// 查询用户数据
	resp, err := u.wxcloud.DatabaseQuery(ctx, u.wxcloud.EnvId(), query)
	if err != nil {
		return nil, fmt.Errorf("failed to query user: %w", err)
	}

	if len(resp.Data) == 0 {
		return nil, fmt.Errorf("user not found with openid: %s", openid)
	}

	// 转换数据
	var user domain.User
	if err := json.Unmarshal([]byte(resp.Data[0]), &user); err == nil {
		return &user, nil
	} else {
		return nil, err
	}
}

// CreateUser 创建新用户
func (u *UserGatewayImpl) CreateUser(ctx context.Context, user *domain.User) error {

	// 设置创建时间和更新时间
	now := time.Now().Unix()
	user.CreateTime = now
	user.UpdateTime = now

	// 设置默认值
	if user.Role == "" {
		user.Role = "normal"
	}
	if user.Status == "" {
		user.Status = "active"
	}

	// 构建新增语句
	query := wxcloud.BuildAddString(userCollection, user)

	// 执行新增操作
	_, err := u.wxcloud.DatabaseAdd(ctx, u.wxcloud.EnvId(), query)
	if err != nil {
		return fmt.Errorf("failed to create user: %w", err)
	}

	return nil
}

// UpdateUser 更新用户信息
func (u *UserGatewayImpl) UpdateUser(ctx context.Context, openid string, user *domain.User) (int, error) {
	// 构建更新条件
	where := map[string]interface{}{
		"openid": openid,
	}

	// 构建只包含非空字段的更新数据
	updateData := make(map[string]interface{})

	// 总是更新时间
	updateData["updateTime"] = time.Now().Unix()

	// 只更新非空字段
	if user.NickName != "" {
		updateData["nickName"] = user.NickName
	}
	if user.AvatarUrl != "" {
		updateData["avatarUrl"] = user.AvatarUrl
	}
	if user.Gender > 0 && user.Gender <= 2 {
		updateData["gender"] = user.Gender
	}
	if user.Country != "" {
		updateData["country"] = user.Country
	}
	if user.Province != "" {
		updateData["province"] = user.Province
	}
	if user.City != "" {
		updateData["city"] = user.City
	}
	if user.Role != "" {
		updateData["role"] = user.Role
	}
	if user.Status != "" {
		updateData["status"] = user.Status
	}

	// 如果没有需要更新的字段（除了updateTime），返回错误
	if len(updateData) == 1 {
		return 0, fmt.Errorf("no fields to update")
	}

	// 构建更新语句
	query := wxcloud.BuildUpdateString(userCollection, where, updateData)

	// 执行更新操作
	matched, modified, err := u.wxcloud.DatabaseUpdate(ctx, u.wxcloud.EnvId(), query)
	if err != nil {
		return 0, fmt.Errorf("failed to update user: %w", err)
	}

	if matched == 0 {
		return 0, nil
	}

	if modified == 0 {
		return 0, nil
	}

	return matched, nil
}

// DeleteUser 删除用户（软删除，设置状态为deleted）
func (u *UserGatewayImpl) DeleteUser(ctx context.Context, openid string) error {

	// 构建更新条件
	where := map[string]interface{}{
		"openid": openid,
	}

	// 构建软删除数据
	updateData := map[string]interface{}{
		"status":     "deleted",
		"updateTime": time.Now().Unix(),
	}

	// 构建更新语句
	query := wxcloud.BuildUpdateString(userCollection, where, updateData)

	// 执行软删除操作
	matched, modified, err := u.wxcloud.DatabaseUpdate(ctx, u.wxcloud.EnvId(), query)
	if err != nil {
		return fmt.Errorf("failed to delete user: %w", err)
	}

	if matched == 0 {
		return fmt.Errorf("user not found with openid: %s", openid)
	}

	if modified == 0 {
		return fmt.Errorf("user delete failed, no records modified")
	}

	return nil
}

// GetUsersByStatus 根据状态查询用户
func (u *UserGatewayImpl) GetUsersByStatus(ctx context.Context, status string) ([]domain.User, error) {

	// 构建查询语句
	query := wxcloud.NewQueryBuilder(userCollection).
		Where("status", status).
		Limit(1000).
		OrderBy("createTime", "desc").
		BuildQueryString()

	// 查询用户数据
	resp, err := u.wxcloud.DatabaseQuery(ctx, u.wxcloud.EnvId(), query)
	if err != nil {
		return nil, fmt.Errorf("failed to query users by status: %w", err)
	}

	// 转换数据
	users := make([]domain.User, 0, len(resp.Data))
	for _, item := range resp.Data {
		var user domain.User
		if err := json.Unmarshal([]byte(item), &user); err == nil {
			users = append(users, user)
		} else {
			return nil, err
		}
	}

	return users, nil
}

// GetVIPUsers 查询VIP用户
func (u *UserGatewayImpl) GetVIPUsers(ctx context.Context) ([]domain.User, error) {

	// 构建查询语句
	query := wxcloud.NewQueryBuilder(userCollection).
		Where("role", "vip").
		Limit(1000).
		OrderBy("createTime", "desc").
		BuildQueryString()

	// 查询用户数据
	resp, err := u.wxcloud.DatabaseQuery(ctx, u.wxcloud.EnvId(), query)
	if err != nil {
		return nil, fmt.Errorf("failed to query VIP users: %w", err)
	}

	// 转换数据
	users := make([]domain.User, 0, len(resp.Data))
	for _, item := range resp.Data {
		var user domain.User
		if err := json.Unmarshal([]byte(item), &user); err == nil {
			users = append(users, user)
		} else {
			return nil, err
		}
	}
	return users, nil
}

// UpdateUserVIP 更新用户VIP信息
func (u *UserGatewayImpl) UpdateUserVIP(ctx context.Context, openid string, vipInfo *domain.VipInfo) (int, error) {

	// 构建更新条件
	where := map[string]interface{}{
		"openid": openid,
	}

	// 构建更新数据
	updateData := map[string]interface{}{
		"role":       "vip",
		"vipInfo":    vipInfo,
		"updateTime": time.Now().Unix(),
	}

	// 构建更新语句
	query := wxcloud.BuildUpdateString(userCollection, where, updateData)

	// 执行更新操作
	matched, modified, err := u.wxcloud.DatabaseUpdate(ctx, u.wxcloud.EnvId(), query)
	if err != nil {
		return 0, fmt.Errorf("failed to update user VIP info: %w", err)
	}

	if matched == 0 {
		return 0, nil
	}

	if modified == 0 {
		return 0, nil
	}

	return matched, nil
}
